import { createRouter, createWebHashHistory, RouteRecord } from 'vue-router'
import Home from 'src/views/Home/index.vue'
import Login from 'src/views/Login/index.vue'
import Register from 'src/views/Register/index.vue'
import Profile from 'src/views/Profile/index.vue'
import Article from 'src/views/Article/index.vue'
import CreateArticle from 'src/views/CreateArticle/index.vue'
import Setting from 'src/views/Setting/index.vue'
import {getToken} from 'src/store'

const routes = [
  {
    path: '/',
    name: 'home',
    component: Home
  },
  {
    path: '/login',
    name: 'login',
    component: Login
  },
  {
    path: '/register',
    name: 'register',
    component: Register
  },
  {
    path: '/create',
    name: 'create',
    component: CreateArticle,
    meta: {
      authorized: true
    }
  },
  {
    path: '/profiles/:username',
    name: 'profile',
    component: Profile,
    meta: {
      authorized: true
    }
  },
  {
    path: '/articles/:slug',
    name: 'articleDetail',
    component: Article,
    props: true
  },
  {
    path: '/settings',
    name: 'settings',
    component: Setting,
    meta: {
      authorized: true
    }
  }
]

const router =  createRouter({
  history: createWebHashHistory(),
  routes
})

router.beforeEach((to,from,next) => {
  if (to.meta.authorized) {
    if (getToken() !== '') next()
    else next('/login')
  } else next()
})

export default router